package com.qf.anno.service.impl;

import com.qf.anno.domain.Account;
import com.qf.anno.domain.Code;
import com.qf.anno.domain.R;
import com.qf.anno.mapper.AccountMapper;
import com.qf.anno.service.AccountService;
import com.qf.anno.web.exhandlers.BussinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public int insert(Account account) {
        return accountMapper.insert(account);
    }

    @Override
    public int delete(Integer id) {
        return accountMapper.delete(id);
    }

    @Override
    public int update(Account account) {
        return accountMapper.update(account);
    }

    @Override
    public List<Account> findAll() {
        return accountMapper.findAll();
    }

    @Override
    public Account findById(Integer id) {
        return accountMapper.findById(id);
    }

    /*
        ① 配置平台事务管理器
        ② 开启spring对事务注解的支持
        ③ 在需要进行事务控制的方法上加上@Transactional
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R transfer(String outName, String inName, Double money) {

        Account inAccount = accountMapper.findByName(inName);
        if (inAccount == null){
            //转入账户不存在 -- 抛出异常
            throw new BussinessException(Code.ACCOUNT_NOT_EXISTS);
        }

        Account outAccount = accountMapper.findByName(outName);
        if (outAccount.getMoney()<money){
            //转出账户金额不足 -- 抛出异常
            throw new BussinessException(Code.ACCOUNT_MONEY_NOT_ENOUGH);
        }

        //开始转账
        accountMapper.updateMoneyByName(money,inName);

//        int i = 1/0;

        accountMapper.updateMoneyByName(-money,outName);

        return R.success("转账成功");
    }
}
